package com.example.configdemo;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class ConfigControllerRefresh {

    private static final Logger logger = LoggerFactory.getLogger(ConfigControllerRefresh.class);

    @RequestMapping("/bus-refresh")
    public ResultVO getConfig(){
        logger.info("start---refresh");
        String authorizeUrl = "http://localhost:9206/actuator/bus-refresh";
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        ResultVO resultVO = sendPostRequest(authorizeUrl,params);
        return resultVO;
    }

    /**
     * 向目的URL发送post请求
     * @param url       目的url
     * @param params    发送的参数
     * @return  ResultVO
     */
    public static ResultVO sendPostRequest(String url, MultiValueMap<String, String> params){
        RestTemplate client = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        HttpMethod method = HttpMethod.POST;
        //application/json;charset=UTF-8
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        //将请求头部和参数合成一个请求
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers);
        //执行HTTP请求，将返回的结构使用ResultVO类格式化
        ResponseEntity<ResultVO> response = client.exchange(url, method, requestEntity, ResultVO.class);

        return response.getBody();
    }
}
